package com.hunter.sign.server.controller;

import java.io.File;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSONObject;
import com.hunter.common.base.BaseController;
import com.hunter.common.util.DateUtil;
import com.hunter.common.util.PropertiesFileUtil;
import com.hunter.common.util.StringUtil;
import com.hunter.common.util.document.Word2PdfUtils;
import com.hunter.common.util.document.WordUtils;
import com.hunter.common.util.document.XwpfUtil;
import com.hunter.sign.common.constant.SignConstant;
import com.hunter.sign.common.constant.SignResult;
import com.hunter.sign.common.constant.SignResultConstant;
import com.hunter.sign.common.util.ParamProcess;
import com.hunter.sign.common.util.biometrics.BmpConver;
import com.hunter.sign.common.util.biometrics.CFingerUtils;
import com.hunter.sign.dao.model.SignContract;
import com.hunter.sign.dao.model.SignUser;
import com.hunter.sign.dao.model.SignUserContract;
import com.hunter.sign.dao.model.SignUserContractExample;
import com.hunter.sign.dao.model.SignWitness;
import com.hunter.sign.dao.model.SignWitnessExample;
import com.hunter.sign.rpc.api.SignContractService;
import com.hunter.sign.rpc.api.SignUserContractService;
import com.hunter.sign.rpc.api.SignWitnessService;
import com.hunter.sign.server.vo.request.ContractCreateReq;
import com.hunter.sign.server.vo.request.ContractSaveBaseInfoReq;
import com.hunter.sign.server.vo.request.ContractSaveUserFingerprintReq;
import com.hunter.sign.server.vo.request.ContractSaveWitnessFingerprintReq;
import com.hunter.sign.server.vo.response.ContractSaveWitnessFingerprintResp;


/**
 * 合同
 * 
 * @author hunter
 * 
 */
@Controller
@RequestMapping(value = "/usercontract")
public class UserContractController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(UserContractController.class);

	@Autowired
	private SignUserContractService signUserContractService;

	@Autowired
	private SignWitnessService signWitnessService;
	
	@Autowired
	private SignContractService signContractService;
	
	/**
	 * 保存基本信息
	 * 
	 * @return
	 */
	@RequestMapping(value = "/saveBaseInfo", method = RequestMethod.POST)
	public void saveBaseInfo(HttpServletRequest request, HttpServletResponse response, ContractSaveBaseInfoReq contractSaveBaseInfoReq) {
		SignUser signUser = (SignUser)request.getAttribute(SignConstant.TOKEN_USER);
		logger.info("用户保存基本信息,userid:"+signUser.getUserId()+",req：" + contractSaveBaseInfoReq);
		// 参数校验失败
		if (!ParamProcess.paramValid(contractSaveBaseInfoReq, ContractSaveBaseInfoReq.class)) {
			outHttpJson(response, new SignResult(SignResultConstant.FAILED, null));
			return;
		}
		logger.info("用户保存基本信息------------参数验证通过");
		//通过用户合同id和用户id获取用户合同
		SignUserContractExample example = new SignUserContractExample();
		example.createCriteria()
        	.andUserContractIdEqualTo(contractSaveBaseInfoReq.getUserContractId())
        	.andUserIdEqualTo(signUser.getUserId())
        	.andStateEqualTo(0);
		SignUserContract signUserContract = signUserContractService.selectFirstByExample(example);
		//用户合同不存在
		if(signUserContract == null){
			outHttpJson(response, new SignResult(SignResultConstant.FAILED, null));
			return;
		}
		logger.info("用户保存基本信息------------更新用户合同信息");
		signUserContract.setContractId(1L);//合同id
		signUserContract.setFieldFill(contractSaveBaseInfoReq.getFieldFill());
		signUserContract.setState(1);
		signUserContractService.updateByPrimaryKey(signUserContract);
		outHttpJson(response, new SignResult(SignResultConstant.SUCCESS, null));
	}
	
	/**
	 * 保存用户指纹
	 * 
	 * @return
	 */
	@RequestMapping(value = "/saveUserFingerprint", method = RequestMethod.POST)
	public void saveUserFingerprint(HttpServletRequest request, HttpServletResponse response, ContractSaveUserFingerprintReq contractSaveUserFingerprintReq) {
		SignUser signUser = (SignUser)request.getAttribute(SignConstant.TOKEN_USER);
		logger.info("保存用户指纹,userid:"+signUser.getUserId()+",req：" + contractSaveUserFingerprintReq);
		// 参数校验失败
		if (!ParamProcess.paramValid(contractSaveUserFingerprintReq, ContractSaveUserFingerprintReq.class)) {
			outHttpJson(response, new SignResult(SignResultConstant.FAILED, null));
			return;
		}
		//通过用户合同id和用户id获取用户合同
		SignUserContractExample example = new SignUserContractExample();
		example.createCriteria()
        	.andUserContractIdEqualTo(contractSaveUserFingerprintReq.getUserContractId())
        	.andUserIdEqualTo(signUser.getUserId())
        	.andStateEqualTo(1);
		SignUserContract signUserContract = signUserContractService.selectFirstByExample(example);
		//用户合同不存在
		if(signUserContract == null){
			outHttpJson(response, new SignResult(SignResultConstant.FAILED, null));
			return;
		}
		String dsetImg = contractSaveUserFingerprintReq.getUserFingerprintImg().replace(".bmp", "")+"conver.bmp";
	    BmpConver.conver(contractSaveUserFingerprintReq.getUserFingerprintImg(), dsetImg);
		//用户指纹信息不符
		if(CFingerUtils.match(dsetImg, signUser.getFingerprintImg())<Double.valueOf(PropertiesFileUtil.getInstance("config").get("finger.match"))){
			outHttpJson(response, new SignResult(SignResultConstant.UNMATCH_USER, null));
			return;
		}
		signUserContract.setUserFingerprintImg(dsetImg);
		signUserContract.setState(2);
		signUserContractService.updateByPrimaryKey(signUserContract);
		outHttpJson(response, new SignResult(SignResultConstant.SUCCESS, null));
	}
	

	/**
	 * 保存见证员指纹
	 * 
	 * @return
	 */
	@RequestMapping(value = "/saveWitnessFingerprint", method = RequestMethod.POST)
	public void saveWitnessFingerprint(HttpServletRequest request, HttpServletResponse response, ContractSaveWitnessFingerprintReq contractSaveWitnessFingerprintReq) {
		SignUser signUser = (SignUser)request.getAttribute(SignConstant.TOKEN_USER);
		logger.info("保存见证员指纹,userid:"+signUser.getUserId()+",req：" + contractSaveWitnessFingerprintReq);
		// 参数校验失败
		if (!ParamProcess.paramValid(contractSaveWitnessFingerprintReq, ContractSaveWitnessFingerprintReq.class)) {
			outHttpJson(response, new SignResult(SignResultConstant.FAILED, null));
			return;
		}
		//通过用户合同id和用户id获取用户合同
		SignUserContractExample example = new SignUserContractExample();
		example.createCriteria()
        	.andUserContractIdEqualTo(contractSaveWitnessFingerprintReq.getUserContractId())
        	.andUserIdEqualTo(signUser.getUserId())
        	.andStateEqualTo(2);
		SignUserContract signUserContract = signUserContractService.selectFirstByExample(example);
		//用户合同不存在
		if(signUserContract == null){
			outHttpJson(response, new SignResult(SignResultConstant.FAILED, null));
			return;
		}
		//获取见证员信息
		SignWitnessExample signWitnessExample = new SignWitnessExample();
		signWitnessExample.createCriteria()
		.andIdTypeEqualTo(contractSaveWitnessFingerprintReq.getWitnessIdType())
		.andIdCardEqualTo(contractSaveWitnessFingerprintReq.getWitnessIdCard());
		SignWitness signWitness = signWitnessService.selectFirstByExample(signWitnessExample);
		//见证员不存在
		if(signWitness == null){
			outHttpJson(response, new SignResult(SignResultConstant.UNKNOWN_WITNESS, null));
			return;
		}
		String dsetImg = contractSaveWitnessFingerprintReq.getWitnessFingerprintImg().replace(".bmp", "")+"conver.bmp";
	    BmpConver.conver(contractSaveWitnessFingerprintReq.getWitnessFingerprintImg(), dsetImg);
		//见证员指纹信息不符
		if(CFingerUtils.match(dsetImg, signWitness.getFingerprintImg())<Double.valueOf(PropertiesFileUtil.getInstance("config").get("finger.match"))){
			outHttpJson(response, new SignResult(SignResultConstant.UNMATCH_WITNESS, null));
			return;
		}
		signUserContract.setWitnessFingerprintImg(dsetImg);
		signUserContract.setState(3);
		//生成word和pdf
		SignContract signContract = signContractService.selectByPrimaryKey(signUserContract.getContractId());
		String basepath = DateUtil.getCurrentDate()+"/"+DateUtil.getCurrentHour();
		String filePath = PropertiesFileUtil.getInstance("config").get("file.path")+"/"+basepath;
		String urlPath = PropertiesFileUtil.getInstance("config").get("file.url")+"/"+basepath;
		File file = new File(filePath);
		if (!file.exists()) {
			file.mkdirs();
		}
		String newFileName = StringUtil.getLongName();
		String contractWord = filePath+"/"+newFileName+".docx";
		String contractPdf = filePath+"/"+newFileName+".pdf";
//		WordUtils.replaceInPara((Map<String, String>)JSONObject.parseObject(signUserContract.getFieldFill(), Map.class), PropertiesFileUtil.getInstance("config").get("file.path")+"/"+"/templet"+"/"+signContract.getModelPath(), contractWord);
		//替换内容
		XwpfUtil.replaceInPara((Map<String, String>)JSONObject.parseObject(signUserContract.getFieldFill(), Map.class), PropertiesFileUtil.getInstance("config").get("file.path")+"/templet"+"/"+signContract.getTempletReplacePath(), contractWord);
		//生成指纹图片
		WordUtils.createTwoPic(signUserContract.getUserFingerprintImg(), signUserContract.getWitnessFingerprintImg(), 150, 150, contractWord, contractWord);
		//生成pdf文档
		Word2PdfUtils.wordToPdf(contractWord, contractPdf);
		signUserContract.setWordUrl(urlPath+"/"+newFileName+".docx");
		signUserContract.setPdfUrl(urlPath+"/"+newFileName+".pdf");
		signUserContractService.updateByPrimaryKey(signUserContract);
		//返回数据
		ContractSaveWitnessFingerprintResp contractSaveWitnessFingerprintResp = new ContractSaveWitnessFingerprintResp();
		contractSaveWitnessFingerprintResp.setContractWord(signUserContract.getWordUrl());
		contractSaveWitnessFingerprintResp.setContractPdf(signUserContract.getPdfUrl());
		outHttpJson(response, new SignResult(SignResultConstant.SUCCESS, contractSaveWitnessFingerprintResp));
	}
	
	/**
	 * 生成合同
	 * 
	 * @return
	 */
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	public void saveWitnessFingerprint(HttpServletRequest request, HttpServletResponse response, ContractCreateReq contractCreateReq) {
		SignUser signUser = (SignUser)request.getAttribute(SignConstant.TOKEN_USER);
		logger.info("生成合同,userid:"+signUser.getUserId()+",req：" + contractCreateReq);
		// 参数校验失败
		if (!ParamProcess.paramValid(contractCreateReq, ContractCreateReq.class)) {
			outHttpJson(response, new SignResult(SignResultConstant.FAILED, null));
			return;
		}
		//通过用户合同id和用户id获取用户合同
		SignUserContractExample example = new SignUserContractExample();
		example.createCriteria()
        	.andUserContractIdEqualTo(contractCreateReq.getUserContractId())
        	.andUserIdEqualTo(signUser.getUserId())
        	.andStateEqualTo(3);
		SignUserContract signUserContract = signUserContractService.selectFirstByExample(example);
		//用户合同不存在
		if(signUserContract == null){
			outHttpJson(response, new SignResult(SignResultConstant.FAILED, null));
			return;
		}
		signUserContract.setState(4);

		//生成word和pdf
//		String basepath = DateUtil.getCurrentDate()+"/"+DateUtil.getCurrentHour();
//		String filePath = PropertiesFileUtil.getInstance("config").get("file.path")+"/"+basepath;
//		String urlPath = PropertiesFileUtil.getInstance("config").get("file.url")+"/"+basepath;
//		File file = new File(filePath);
//		if (!file.exists()) {
//			file.mkdirs();
//		}
//		String newFileName = StringUtil.getLongName();
//		String contractWord = filePath+"/"+newFileName+".docx";
//		String contractPdf = filePath+"/"+newFileName+".pdf";
//		WordUtils.createTwoPic(signUserContract.getUserFingerprintImg(), signUserContract.getWitnessFingerprintImg(), 200, 200, signUserContract.getWordUrl().replace(PropertiesFileUtil.getInstance("config").get("file.url"),PropertiesFileUtil.getInstance("config").get("file.path")), contractWord);
//		Word2PdfUtils.wordToPdf(contractWord, contractPdf);
//		signUserContract.setWordUrl(urlPath+"/"+newFileName+".docx");
//		signUserContract.setPdfUrl(urlPath+"/"+newFileName+".pdf");
		signUserContractService.updateByPrimaryKey(signUserContract);
		
		//返回数据
		ContractSaveWitnessFingerprintResp contractSaveWitnessFingerprintResp = new ContractSaveWitnessFingerprintResp();
		contractSaveWitnessFingerprintResp.setContractWord(signUserContract.getWordUrl());
		contractSaveWitnessFingerprintResp.setContractPdf(signUserContract.getPdfUrl());
		outHttpJson(response, new SignResult(SignResultConstant.SUCCESS, contractSaveWitnessFingerprintResp));
	}
}
